using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;

namespace DBProBridge
{
    public static class SerializationUtility
    {
        public static void Serialize2File<T>(T source, string fileName)
        {
            System.Xml.Serialization.XmlSerializer xs = null;
            System.IO.TextWriter tw = null;

            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(fileName))) Directory.CreateDirectory(Path.GetDirectoryName(fileName));

                xs = new System.Xml.Serialization.XmlSerializer(typeof(T));

                tw = new StreamWriter(fileName, false);

                xs.Serialize(tw, source);

            }
            finally
            {
                if (tw != null) tw.Close();
            }
        }

        public static T DeserializeFromFile<T>(string path)
        {
            if (!File.Exists(path)) return default(T);

            object ctc = null;

            if (path != null || path != String.Empty)
            {
                System.Xml.XmlTextReader reader = null;

                try
                {
                    System.Xml.Serialization.XmlSerializer xs = new XmlSerializer(typeof(T));
                    reader = new XmlTextReader(path);
                    reader.Normalization = false;

                    ctc = xs.Deserialize(reader);
                }
                finally
                {
                    if (reader != null) reader.Close();
                }
            }
            return (T)ctc;
        }

    }
}
